<?php


namespace app\api\service;


use app\api\model\Address;
use app\api\model\Language;
use app\api\model\LanguageGrade;
use app\common\model\BaseModel;
use app\api\model\Course;
use app\api\model\CourseOrder;
use app\api\model\TeacherCourse;
use think\Cache;
use think\Db;

class CourseOrderService
{
    /**
     * 创建订单
     */
    public function create($data)
    {
        $courseOrderModel = new CourseOrder();
        $courseModel = new Course();
        Db::startTrans();
        try {
            $courseOrderModel->add($this->orderData($data));
            //课表
            $reserve = false;
            if (isset($data['course']) && $data['course']) {
                $reserve = true;
            }
            $courseData = $this->courseData($courseOrderModel, $data, $reserve);
            $courseModel->addAll($courseData);

            Db::commit();
            return $courseOrderModel;
        } catch (\Exception $e) {
            Db::rollback();
            return false;
        }
    }

    /**
     * 订单数据
     */
    private function orderData($data)
    {
        //订单号
        $order_no = date('YmdHis').$data['user_id'].mt_rand(1000, 9999);
        //课程
        $teacherCoure = TeacherCourse::find($data['teacher_course_id']);
        if (!$teacherCoure) {
            BaseModel::error(10001);
        }
        //语种
        $language = Language::find($teacherCoure->language_id);
        //语种等级
        $languageGrade = LanguageGrade::find($teacherCoure->language_grade_id);
        //地址
        $address = $data['address'];
        if (isset($data['address_id']) && $data['address_id']) {
            $UserAddress = Address::with(['province', 'city', 'area'])->find($data['address_id']);
            if (!$UserAddress) {
                BaseModel::error(11001);
            }
            $province = $UserAddress->province ? $UserAddress->province->name : '';
            $city = $UserAddress->city ? $UserAddress->city->name : '';
            $area = $UserAddress->area ? $UserAddress->area->name : '';
            $address = $province.' '.$city.' '.$area.' '.$UserAddress->address;
        }


        //订单数据
        return [
            'teacher_course_id' => $teacherCoure->teacher_course_id,
            'teacher_id' => $teacherCoure->teacher_id,
            'user_id' => $data['user_id'],
            'classdata' => $data['classdata'],
            'address_id' => $data['address_id'],
            'order_no' => $order_no,
            'language' => $language ? $language->title : '',
            'language_grade' => $languageGrade ? $languageGrade->title : '',
            'username' => $data['username'],
            'phone' => $data['phone'],
            'address' => $address,
            'price' => $teacherCoure->price,
            'hour' => $teacherCoure->hour,
            'num' => $data['num'],
            'total_hour' => $data['num'] * $teacherCoure->hour,
            'total_price' => $data['num'] * $teacherCoure->price,
            'status' => 1
        ];
    }

    /**
     * 课表数据
     */
    private function courseData($courseOrder, $data, $reserve = true)
    {
        $course = [];
        for ($i = 0; $i < $data['num']; $i++) {
            $date = $reserve ? $data['course'][$i]['date'] : '';
            $week = $reserve ? getWeek($date) : '';
            $time = $reserve ? reserveTime($data['course'][$i]['time']) : '';
            $course[] = [
                'course_order_id' => $courseOrder->course_order_id,
                'teacher_course_id' => $data['teacher_course_id'],
                'teacher_id' => $courseOrder->teacher_id,
                'user_id' => $courseOrder->user_id,
                'date' => $date,
                'week' => $week,
                'time' => $time,
                'index' => $i + 1
            ];
        }
        return $course;
    }

    /**
     * 用户订单
     */
    public static function getUserOrders($userId, $status, $size)
    {
        $orderStatus = self::orderStatus($status);
        $orders = CourseOrder::getUserOrders($userId, $orderStatus, $size);
        return $orders;
    }

    /**
     * 订单状态
     */
    private static function orderStatus($status)
    {
        switch ($status) {
            //待支付
            case 1:
                return [1];
                break;
            //待上课
            case 2:
                return [2];
                break;
            //已完成
            case 3:
                return [3];
                break;
            //取消、退款
            case 4:
                return [0, 4, 5, 6];
                break;
            //全部
            default:
                return [0, 1, 2, 3, 4, 5, 6];
                break;
        }
    }
}